<?php

namespace app\data\command;

use app\data\model\ShopOrder;
use app\data\model\ShopOrderDetail;
use app\data\service\OrderService;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;
use think\Model;

/**
 * 商城订单自动清理
 * Class OrderClean
 * @package app\data\command
 */
class OrderClean extends Command
{
    protected function configure()
    {
        $this->setName('xdata:OrderClean');
        $this->setDescription('批量清理商城订单数据');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $this->_autoCancelOrder();
        $this->_autoRemoveOrder();
    }
    /**
     * 2小时未支付取消支付   3天取消订单会删除
     */
    /**
     * 自动取消2小时未支付的订单
     * @throws Exception
     */
    private function _autoCancelOrder()
    {
        try {
            $map = [['status', '<', 4], ['status', '>', 0],['payment_status', '=', 0]];
            $map[] = ['create_at', '<', date('Y-m-d H:i:s', strtotime('-2 hours'))];
            [$count, $total] = [0, ($result = ShopOrder::mk()->where($map)->select())->count()];
            $result->map(function (Model $item) use ($total, &$count) {
                $opera = [];
                $this->queue->message($total, ++$count, "开始取消未支付的订单 {$item['order_no']}");
                $opera[] = $item->save(['status' => 0, 'cancel_datetime' => date('Y-m-d H:i:s'), 'cancel_remark' => '自动取消2小时内未完成支付']);
                //归还库存
                $opera = OrderService::stock($item['order_no'],$opera,1);
                //解冻冻结的数据
                 //如果订单有佣金抵扣  归还佣金
                if ($item['payment_balance'] > 0){
                    $DatauserAccountModel = new \app\api\model\DataUserAccount();
                    $opera[] = $DatauserAccountModel->incNum(['uuid'=>$item['uuid']],'avail_amount',$item['payment_balance']);
                    $opera[] = $DatauserAccountModel->decNum(['uuid'=>$item['uuid']],'freeze_amount',$item['payment_balance']);
                }
                sysoplog('取消订单','系统：超时取消订单：'.$item['order_no']);

                if(\Tools::checkArrayResult($opera)){

                }else{
                    //TODO 发短信警告
                    sysoplog('取消订单失败','系统：超时取消订单：失败，订单号为：'.$item['order_no'].'状态：'.json_encode($opera));
                }
                //TODO 优惠券
                //TODO 积分
                $this->queue->message($total, $count, "完成取消未支付的订单 {$item['order_no']}", 1);
            });
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage());
        }
    }

    /**
     * 自动清理已经取消的订单
     * @throws Exception
     */
    private function _autoRemoveOrder()
    {
        try {
            $map = [['status', '=', 0], ['payment_status', '=', 0]];
            $map[] = ['create_at', '<', date('Y-m-d H:i:s', strtotime('-3 days'))];
            [$count, $total] = [0, ($result = ShopOrder::mk()->where($map)->select())->count()];
            $result->map(function (Model $item) use ($total, &$count) {
                $this->queue->message($total, ++$count, "开始清理已取消的订单 {$item['order_no']}");
                ShopOrder::mk()->where(['order_no' => $item['order_no']])->delete();
                ShopOrderDetail::mk()->where(['order_no' => $item['order_no']])->delete();
                $this->queue->message($total, $count, "完成清理已取消的订单 {$item['order_no']}", 1);
            });
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage());
        }
    }
}
